package com.zsc.oj.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.oj.common.ErrorCode;
import com.zsc.oj.constant.CommonConstant;
import com.zsc.oj.exception.BusinessException;
import com.zsc.oj.exception.ThrowUtils;
import com.zsc.oj.mapper.TbCommentMapper;
import com.zsc.oj.model.dto.tbComment.TbCommentQueryRequest;
import com.zsc.oj.model.entity.TbComment;
import com.zsc.oj.model.entity.User;
import com.zsc.oj.model.vo.TbCommentVO;
import com.zsc.oj.model.vo.UserVO;
import com.zsc.oj.service.TbCommentService;
import com.zsc.oj.service.UserService;
import com.zsc.oj.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 评论服务实现
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@Service
@Slf4j
public class TbCommentServiceImpl extends ServiceImpl<TbCommentMapper, TbComment> implements TbCommentService {

    @Resource
    private UserService userService;

    /**
     * 校验数据
     *
     * @param tbComment
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validTbComment(TbComment tbComment, boolean add) {
        ThrowUtils.throwIf(tbComment == null, ErrorCode.PARAMS_ERROR);
        // todo 从对象中取值
        String content = tbComment.getContent();
        Long userId = tbComment.getUserId();
        Long questionId = tbComment.getQuestionId();


        // 创建数据时，参数不能为空
        if (add) {
            // todo 补充校验规则
            ThrowUtils.throwIf(StringUtils.isBlank(content), ErrorCode.PARAMS_ERROR,"评论内容不能为空");
            ThrowUtils.throwIf(userId == null, ErrorCode.PARAMS_ERROR,"创建人id不能为空");
            ThrowUtils.throwIf(questionId == null, ErrorCode.PARAMS_ERROR,"题目id不能为空");
        }
        // 修改数据时，有参数则校验
        // todo 补充校验规则
        if (StringUtils.isNotBlank(content)) {
            ThrowUtils.throwIf(content.length() > 1024, ErrorCode.PARAMS_ERROR, "内容过长!");
        }
    }

    /**
     * 获取查询条件
     *
     * @param tbCommentQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<TbComment> getQueryWrapper(TbCommentQueryRequest tbCommentQueryRequest) {
        QueryWrapper<TbComment> queryWrapper = new QueryWrapper<>();
        if (tbCommentQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = tbCommentQueryRequest.getId();
        Long notId = tbCommentQueryRequest.getNotId();
        String content = tbCommentQueryRequest.getContent();
        String searchText = tbCommentQueryRequest.getSearchText();
        String sortField = tbCommentQueryRequest.getSortField();
        String sortOrder = tbCommentQueryRequest.getSortOrder();
        Long userId = tbCommentQueryRequest.getUserId();
        Long questionId = tbCommentQueryRequest.getQuestionId();

        if(questionId == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"题目id不能为空");
        }

        // todo 补充需要的查询条件
        // 从多字段中搜索
        if (StringUtils.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content", searchText));
        }
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        // JSON 数组查询

        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);

        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取评论封装
     *
     * @param tbComment
     * @param request
     * @return
     */
    @Override
    public TbCommentVO getTbCommentVO(TbComment tbComment, HttpServletRequest request) {
        // 对象转封装类
        TbCommentVO tbCommentVO = TbCommentVO.objToVo(tbComment);

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = tbComment.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        tbCommentVO.setUser(userVO);

        // endregion

        return tbCommentVO;
    }

    /**
     * 分页获取评论封装
     *
     * @param tbCommentPage
     * @param request
     * @return
     */
    @Override
    public Page<TbCommentVO> getTbCommentVOPage(Page<TbComment> tbCommentPage, HttpServletRequest request) {
        List<TbComment> tbCommentList = tbCommentPage.getRecords();
        Page<TbCommentVO> tbCommentVOPage = new Page<>(tbCommentPage.getCurrent(), tbCommentPage.getSize(), tbCommentPage.getTotal());
        if (CollUtil.isEmpty(tbCommentList)) {
            return tbCommentVOPage;
        }
        // 对象列表 => 封装对象列表
        List<TbCommentVO> tbCommentVOList = tbCommentList.stream().map(tbComment -> {
            return TbCommentVO.objToVo(tbComment);
        }).collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息

        for (TbCommentVO tbCommentVO : tbCommentVOList) {
            Long userId = tbCommentVO.getUserId();
            User user = userService.getById(userId);
            UserVO userVO = UserVO.objToVo(user);
            tbCommentVO.setUser(userVO);
        }
//        Set<Long> userIdSet = tbCommentList.stream().map(TbComment::getUserId).collect(Collectors.toSet());
//        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
//                .collect(Collectors.groupingBy(User::getId));
        // endregion

        tbCommentVOPage.setRecords(tbCommentVOList);
        return tbCommentVOPage;
    }

}
